<template>
	<div class="wrapper">
		<!-- 模板内容保持不变 -->
				
		<!-- header部分 -->
		<header>
			<button class="back-btn" @click="handleBack">← 返回</button>
			<p>商家信息</p>
		</header>
		
		<!-- 商家logo部分 -->
		<div class="business-logo">
			<img :src="business.businessImg || defaultBusinessImg" alt="商家logo">
		</div>
		
		<!-- 商家信息部分 -->
		<div class="business-info">
			<h1>{{business.businessName || '加载中...'}}</h1>
			<p>&#165;{{business.startPrice || 0}}起送 &#165;{{business.deliveryPrice || 0}}配送</p>
			<p>{{business.businessExplain || '暂无商家介绍'}}</p>
			<p>{{business.businessAddress || '暂无地址信息'}}</p>
		</div>
		
		<!-- 食品列表部分 -->
		<ul class="food">
			<li v-for="(item,index) in foodArr" :key="item.id">
				<div class="food-left">
					<img :src="item.foodImg || defaultFoodImg" alt="商品图片">
					<div class="food-left-info">
						<h3>{{item.foodName}}</h3>
						<p>{{item.foodExplain}}</p>
						<p>&#165;{{item.foodPrice}}</p>
					</div>
				</div>
				<div class="food-right">
					<div>
						<i class="fa fa-minus-circle" @click="minus(index)" v-show="item.quantity > 0"></i>
					</div>
					<p><span v-show="item.quantity > 0">{{item.quantity}}</span></p>
					<div>
						<i class="fa fa-plus-circle" @click="() => add(index)"></i>
					</div>
				</div>
			</li>
		</ul>
		
		<!-- 购物车部分 -->
		<div class="cart">
		  <div class="cart-left" @click="toggleCartPanel">
		    <div class="cart-left-icon" :style="totalQuantity === 0 ? 'background-color:#505051;' : 'background-color:#3190E8;'">
		      <i class="fa fa-shopping-cart"></i>
		      <div class="cart-left-icon-quantity" v-show="totalQuantity > 0">{{totalQuantity}}</div>
		    </div>
		    <div class="cart-left-info">
		      <p>&#165;{{totalPrice}}</p>
		      <p>另需配送费{{business.deliveryPrice || 0}}元</p>
		    </div>
		  </div>
		  <div class="cart-right">
		    <div class="cart-right-item" v-show="totalSettle < (business.startPrice || 0)" style="background-color: #535356;cursor: default;">
		      &#165;{{business.startPrice || 0}}起送
		    </div>
		    <div class="cart-right-item" @click="toOrder" v-show="totalSettle >= (business.startPrice || 0)">
		      去结算
		    </div>
		  </div>
		</div>
		
		<!-- 购物车详情面板 -->
		<div class="cart-panel" v-if="showCartPanel">
		  <div class="cart-panel-header">
		    <h3>购物车</h3>
		    <span class="close-btn" @click="showCartPanel = false">×</span>
		  </div>
		  <div class="cart-panel-content">
		    <div v-if="totalQuantity === 0" class="empty-cart">
		      <p>购物车是空的</p>
		    </div>
		    <div v-else>
		      <div v-for="(item, index) in foodArr" :key="index" v-if="item.quantity > 0" class="cart-panel-item">
		        <div class="item-info">
		          <h4>{{ item.foodName }}</h4>
		          <p>¥{{ item.foodPrice }}</p>
		        </div>
		        <div class="item-quantity">
		          <button @click="minus(index)">-</button>
		          <span>{{ item.quantity }}</span>
		          <button @click="add(index)">+</button>
		        </div>
		      </div>
		    </div>
		  </div>
		  <div class="cart-panel-footer">
		    <p>总计: ¥{{ totalPrice }}</p>
		    <p v-if="totalPrice < business.startPrice" class="shipping-tip">
		      还差 ¥{{ (business.startPrice - totalPrice).toFixed(2) }} 起送
		    </p>
		    <p v-else class="shipping-tip">已达到起送金额</p>
		    <button class="checkout-btn-panel" @click="toOrder" :disabled="totalPrice < business.startPrice">
		      去结算
		    </button>
		  </div>
		</div>
		
		<!-- 购物车遮罩层 -->
		<div class="cart-panel-mask" v-if="showCartPanel" @click="showCartPanel = false"></div>
		
	</div>
</template>

<script>
	export default{
		name:'BusinessInfo',
		data(){
			return {
				businessId: this.$route.params.businessId || this.$route.query.businessId,
				business:{},
				foodArr:[],
				cartItems: [], // 存储购物车项
				defaultBusinessImg: require('@/assets/sj01.png'),
				defaultFoodImg: require('@/assets/sp01.png'),
				showCartPanel: false, // 控制购物车详情面板显示
			}
		},
		computed: {
			isLoggedIn() {
				// 改为从localStorage读取用户信息
				const storedUser = this.$getLocalStorage('user');
				return !!storedUser;
			},
			userInfo() {
				// 改为从localStorage读取用户信息
				return this.$getLocalStorage('user') || {};
			},
			totalPrice(){
				let total = 0;
				for(let item of this.foodArr){
					if (item && item.foodPrice && item.quantity) {
						total += item.foodPrice * item.quantity;
					}
				}
				return total.toFixed(2);
			},
			totalQuantity(){
				let quantity = 0;
				for(let item of this.foodArr){
					if (item && item.quantity) {
						quantity += item.quantity;
					}
				}
				return quantity;
			},
			totalSettle(){
				return this.totalPrice * 1 + (this.business?.deliveryPrice || 0);
			}
		},
		created() {
			this.fetchBusinessDetail();
			this.fetchBusinessFoods();
		},
		methods:{
			handleToLogin() {
				this.$router.push({
					path: '/login',
					query: { redirect: this.$route.fullPath }
				});
			},
			// 切换购物车面板显示	
			toggleCartPanel() {
			    if (this.totalQuantity > 0) {
			      this.showCartPanel = !this.showCartPanel;
			    }
			},
			
			async fetchBusinessDetail() {
				try {
					console.log('获取商家详情, ID:', this.businessId);
					const response = await this.$axios.get(`/api/businesses/${this.businessId}`);
					console.log('商家详情响应:', response.data);
					if (response.data.success && response.data.data) {
						this.business = response.data.data;
					} else {
						console.error('获取商家详情失败:', response.data.message);
						alert('获取商家信息失败: ' + (response.data.message || '未知错误'));
					}
				} catch (error) {
					console.error('请求商家详情接口出错:', error);
					alert('网络错误，无法获取商家信息');
				}
			},
			
			async fetchBusinessFoods() {
				try {
					console.log('获取商家商品列表, 商家ID:', this.businessId);
					const response = await this.$axios.get(`/api/public/foods/business/${this.businessId}`);
					console.log('商品列表响应:', response.data);
					if (response.data.success && response.data.data) {
						this.foodArr = response.data.data.map(item => ({
							...item,
							quantity: 0
						}));
						
						if (this.isLoggedIn) {
							this.listCart();
						}
					} else {
						console.error('获取商品列表失败:', response.data.message);
						alert('获取商品列表失败: ' + (response.data.message || '未知错误'));
					}
				} catch (error) {
					console.error('请求商品列表接口出错:', error);
					alert('网络错误，无法获取商品列表');
				}
			},
			
			async listCart() {
				try {
					// 关键修改：调用购物车接口时添加businessId参数
					console.log('获取当前商家购物车列表, 商家ID:', this.businessId, '用户ID:', this.userInfo.id);
					const headers = {
						'Authorization': `Bearer ${this.userInfo.token || ''}`
					};
					
					// 传递businessId参数，确保只获取当前商家的购物车商品
					const response = await this.$axios.get('/api/carts', { 
						params: { businessId: this.businessId },
						headers 
					});
					
					console.log('当前商家购物车列表响应:', response.data);
					// 解析响应数据，适配接口返回格式
					const cartData = response.data.success ? response.data.data : response.data;
					
					if (Array.isArray(cartData)) {
						this.cartItems = cartData;
						
						// 只同步当前商家的购物车数量
						this.foodArr.forEach(foodItem => {
							const cartItem = cartData.find(
								item => item?.business?.id == this.businessId && item?.food?.id == foodItem.id
							);
							
							if (cartItem) {
								foodItem.quantity = cartItem.quantity || 0;
								console.log(`同步购物车数据: ${foodItem.foodName} 数量: ${foodItem.quantity}`);
							}
						});
					} else {
						this.cartItems = [];
					}
				} catch (error) {
					console.error('请求购物车接口出错:', error);
					this.cartItems = [];
					if (error.response?.status === 401) {
						// 改为清除localStorage中的用户信息
						this.$removeLocalStorage('user');
						alert('登录已失效，请重新登录');
						this.handleToLogin();
					}
				}
			},
			
			add(index) {
				if (!this.isLoggedIn) {
					console.log('用户未登录，跳转到登录页');
					this.handleToLogin();
					return;
				}
				
				console.log('添加商品, 索引:', index);
				
				if (index === undefined || index < 0 || index >= this.foodArr.length) {
					console.error('无效的商品索引:', index);
					alert('无效的商品');
					return;
				}
				
				const food = this.foodArr[index];
				if (!food || !food.id) {
					console.error('无效的商品数据:', food);
					alert('无效的商品数据');
					return;
				}
				
				console.log('准备添加商品:', food.foodName, '当前数量:', food.quantity);
				
				// 查找购物车中是否已有该商品（当前商家）
				const cartItem = this.cartItems.find(
					item => item?.business?.id == this.businessId && item?.food?.id == food.id
				);
				
				if (cartItem && cartItem.id) {
					// 购物车中已有该商品，更新数量
					console.log(`购物车中已有该商品，ID: ${cartItem.id}，更新数量`);
					this.updateCart(cartItem.id, index, 1);
				} else {
					// 购物车中没有该商品，添加新商品
					console.log('购物车中没有该商品，添加新商品');
					this.saveCart(index);
				}
			},
			
			minus(index) {
				if (!this.isLoggedIn) {
					this.handleToLogin();
					return;
				}
				
				console.log('减少商品, 索引:', index);
				
				if (index === undefined || index < 0 || index >= this.foodArr.length) {
					console.error('无效的商品索引:', index);
					return;
				}
				
				const food = this.foodArr[index];
				if (!food || !food.id) {
					console.error('无效的商品数据:', food);
					return;
				}
				
				if(food.quantity > 0) {
					const cartItem = this.cartItems.find(
						item => item?.business?.id == this.businessId && item?.food?.id == food.id
					);
					
					if (cartItem && cartItem.id) {
						if (food.quantity === 1) {
							this.removeCart(cartItem.id, index);
						} else {
							this.updateCart(cartItem.id, index, -1);
						}
					}
				}
			},
			
			async saveCart(index) {
				try {
					const food = this.foodArr[index];
					if (!food || !food.id) {
						console.error('无效的商品数据:', food);
						return;
					}
					
					console.log('添加新商品到购物车:', food.foodName);
					
					const cartData = {
						"food": {
							"id": food.id
						},
						"business": {
							"id": this.businessId
						},
						"customer": {
							"id": this.userInfo.id
						},
						"quantity": 1,
						"deleted": false
					};
					
					console.log('发送添加请求:', cartData);
					
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': `Bearer ${this.userInfo.token || ''}`
					};
					const response = await this.$axios.post('/api/carts', cartData, { headers });
					
					console.log('添加商品响应:', response.data);
					
					// 修复：无论响应结构如何，只要成功就更新本地状态
					if (response.data?.success || response.data?.id) {
						// 从响应中提取购物车项ID
						const newCartItem = response.data.data || response.data;
						
						// 强制更新本地数量
						this.foodArr[index].quantity = 1;
						
						// 添加到购物车数组
						if (newCartItem.id) {
							this.cartItems.push(newCartItem);
						}
						
						console.log(`添加成功，当前数量: ${this.foodArr[index].quantity}`);
						alert('商品已添加到购物车');
					} else {
						alert('向购物车中添加食品失败！');
					}
				} catch (error) {
					console.error('添加商品出错:', error);
					alert('添加失败，请重试: ' + (error.message || '网络错误'));
					if (error.response?.status === 401) {
						// 改为清除localStorage中的用户信息
						this.$removeLocalStorage('user');
						alert('登录已失效，请重新登录');
						this.handleToLogin();
					}
				}
			},
			
			async updateCart(cartId, index, num) {
				try {
					const food = this.foodArr[index];
					if (!food || !food.id) {
						console.error('无效的商品数据:', food);
						return;
					}
					
					const newQuantity = this.foodArr[index].quantity + num;
					if (newQuantity < 0) return;
					
					console.log(`更新购物车数量: ${food.foodName} 从 ${food.quantity} 到 ${newQuantity}`);
					
					const updateData = {
						"id": cartId,
						"food": {
							"id": this.foodArr[index].id
						},
						"business": {
							"id": this.businessId
						},
						"customer": {
							"id": this.userInfo.id
						},
						"quantity": newQuantity,
						"deleted": false
					};
					
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': `Bearer ${this.userInfo.token || ''}`
					};
					const response = await this.$axios.put(`/api/carts/${cartId}`, updateData, { headers });
					
					console.log('更新数量响应:', response.data);
					
					// 修复：调整响应判断方式
					if (response.data?.success || response.data) {
						// 强制更新本地数量
						this.foodArr[index].quantity = newQuantity;
						
						// 更新本地购物车数组
						const cartIndex = this.cartItems.findIndex(item => item?.id === cartId);
						if (cartIndex !== -1) {
							this.cartItems[cartIndex] = response.data.data || response.data;
						}
						
						console.log(`更新成功，当前数量: ${this.foodArr[index].quantity}`);
					} else {
						alert('更新购物车失败！');
					}
				} catch (error) {
					console.error('更新商品数量出错:', error);
					let errorMsg = '更新失败: ';
					if (error.response) {
						errorMsg += `状态码: ${error.response.status}, 信息: ${JSON.stringify(error.response.data)}`;
					} else {
						errorMsg += error.message || '未知错误';
					}
					alert(errorMsg);
					
					if (error.response?.status === 401) {
						// 改为清除localStorage中的用户信息
						this.$removeLocalStorage('user');
						alert('登录已失效，请重新登录');
						this.handleToLogin();
					}
				}
			},
			
			async removeCart(cartId, index) {
				try {
					console.log('从购物车移除商品, ID:', cartId);
					
					const headers = {
						'Authorization': `Bearer ${this.userInfo.token || ''}`
					};
					const response = await this.$axios.delete(`/api/carts/${cartId}`, { headers });
					
					console.log('移除商品响应:', response);
					
					if (response.status === 204 || response.data?.success) {
						this.foodArr[index].quantity = 0;
						this.cartItems = this.cartItems.filter(item => item?.id !== cartId);
					} else {
						alert('从购物车中删除食品失败！');
					}
				} catch (error) {
					console.error('删除商品出错:', error);
					alert('删除失败，请重试');
					if (error.response?.status === 401) {
						// 改为清除localStorage中的用户信息
						this.$removeLocalStorage('user');
						alert('登录已失效，请重新登录');
						this.handleToLogin();
					}
				}
			},
			
			toOrder(){
				if (!this.isLoggedIn) {
					this.handleToLogin();
					return;
				}
				this.$router.push({path:'/orders',query:{businessId: this.businessId}});
			},
			
			// 返回上一页
			  handleBack() {
			    this.$router.go(-1); // 返回上一页
			    // 或者使用具体路径：this.$router.push('/businessShopManage');
			  },
		}
	}
</script>
<style scoped>
	/* 样式保持不变 */
	.wrapper{
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}
	
	.wrapper header{
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;
		
	
		
		left: 0;
		top: 0;
		z-index: 1000;
		
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative; /* 添加这行，使绝对定位的子元素相对于此元素定位 */
	}
	
	.back-btn {
	  position: absolute;
	  left: 4vw;
	  background: rgba(255, 255, 255, 0.2);
	  border: none;
	  color: white;
	  padding: 1.5vw 3vw;
	  border-radius: 4px;
	  font-size: 3.2vw;
	  cursor: pointer;
	  transition: background 0.3s ease;
	}
	
	.back-btn:hover {
	  background: rgba(255, 255, 255, 0.3);
	}
	
	.wrapper .business-logo{
		width: 100%;
		height: 35vw;
		margin-top: 12vw;
		background-color: #fff;
		
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.wrapper .business-logo img{
		width: 40vw;
		height: 30vw;
		object-fit: cover;
		border-radius: 5px;
	}
	
	.wrapper .business-info{
		width: 100%;
		min-height: 20vw;
		padding: 3vw;
		box-sizing: border-box;
		background-color: #fff;
		margin-bottom: 2vw;
		
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.wrapper .business-info h1{
		font-size: 5vw;
		color: #333;
	}
	.wrapper .business-info p{
		font-size: 3vw;
		color: #666;
		margin-top: 1vw;
		text-align: center;
	}
	
	.wrapper .food{
		width: 100%;
		padding: 0 2vw;
		box-sizing: border-box;
		list-style: none;
		margin-bottom: 14vw;
	}
	.wrapper .food li{
		width: 100%;
		padding: 2.5vw;
		box-sizing: border-box;
		background-color: #fff;
		margin-bottom: 2vw;
		border-radius: 8px;
		user-select: none;
		
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.wrapper .food li .food-left{
		display: flex;
		align-items: center;
	}
	.wrapper .food li .food-left img{
		width: 20vw;
		height: 20vw;
		object-fit: cover;
		border-radius: 5px;
	}
	.wrapper .food li .food-left .food-left-info{
		margin-left: 3vw;
	}
	.wrapper .food li .food-left .food-left-info h3{
		font-size: 3.8vw;
		color: #333;
	}
	.wrapper .food li .food-left .food-left-info p{
		font-size: 3vw;
		color: #888;
		margin-top: 2vw;
	}
	.wrapper .food li .food-right{
		width: 16vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.wrapper .food li .food-right .fa-minus-circle{
		font-size: 5.5vw;
		color: #999;
		cursor: pointer;
	}
	.wrapper .food li .food-right p{
		font-size: 3.6vw;
		color: #333;
	}
	.wrapper .food li .food-right .fa-plus-circle{
		font-size: 5.5vw;
		color: #0097EF;
		cursor: pointer;
		padding: 5px;
	}
	
	.wrapper .cart{
		width: 100%;
		height: 14vw;
		
		position: fixed;
		left: 0;
		bottom: 0;
		
		display: flex;
	}
	.wrapper .cart .cart-left{
		flex: 2;
		background-color: #505051;
		display: flex;
		cursor: pointer; /* 添加这行 */
	}
	.wrapper .cart .cart-left .cart-left-icon{
		width: 16vw;
		height: 16vw;
		box-sizing: border-box;
		border: solid 1.6vw #444;
		border-radius: 8vw;
		background-color: #3190E8;
		font-size: 7vw;
		color: #fff;
		
		display: flex;
		justify-content: center;
		align-items: center;
		
		margin-top: -4vw;
		margin-left: 3vw;
		
		position: relative;
	}
	.wrapper .cart .cart-left .cart-left-icon-quantity{
		width: 5vw;
		height: 5vw;
		border-radius: 2.5vw;
		background-color: red;
		color: #fff;
		font-size: 3.6vw;
		
		display: flex;
		justify-content: center;
		align-items: center;
		
		position: absolute;
		right: -1.5vw;
		top: -1.5vw;
	}
	
	
	.wrapper .cart .cart-left .cart-left-info {
		margin-left: 3vw;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	.wrapper .cart .cart-left .cart-left-info p:first-child{
		font-size: 4.5vw;
		color: #fff;
		margin-top: 1vw;
	}
	.wrapper .cart .cart-left .cart-left-info p:last-child{
		font-size: 2.8vw;
		color: #AAA;
	}
	
	.wrapper .cart .cart-right{
		flex: 1;
	}
	.wrapper .cart .cart-right .cart-right-item{
		width: 100%;
		height: 100%;
		background-color: #38CA73;
		color: #fff;
		font-size: 4.5vw;
		font-weight: 700;
		user-select: none;
		cursor: pointer;
		
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	/* 购物车面板 */
	.cart-panel {
	  position: fixed;
	  bottom: 14vw;
	  left: 0;
	  width: 100%;
	  background: #fff;
	  z-index: 1002;
	  max-height: 60vh;
	  overflow-y: auto;
	  border-radius: 12px 12px 0 0;
	  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	}
	
	.cart-panel-header {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 4vw;
	  border-bottom: 1px solid #eee;
	  position: sticky;
	  top: 0;
	  background: #fff;
	  z-index: 1;
	}
	
	.cart-panel-header h3 {
	  font-size: 4.5vw;
	  color: #333;
	}
	
	.close-btn {
	  font-size: 6vw;
	  color: #999;
	  cursor: pointer;
	}
	
	.cart-panel-content {
	  padding: 4vw;
	}
	
	.cart-panel-item {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 3vw 0;
	  border-bottom: 1px solid #f5f5f5;
	}
	
	.cart-panel-item:last-child {
	  border-bottom: none;
	}
	
	.cart-panel-item .item-info h4 {
	  font-size: 4vw;
	  color: #333;
	  margin-bottom: 1vw;
	}
	
	.cart-panel-item .item-info p {
	  font-size: 3.5vw;
	  color: #ff5339;
	}
	
	.item-quantity {
	  display: flex;
	  align-items: center;
	}
	
	.item-quantity button {
	  width: 8vw;
	  height: 8vw;
	  border-radius: 50%;
	  border: 1px solid #ddd;
	  background: #f8f8f8;
	  font-size: 4vw;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	.item-quantity span {
	  margin: 0 3vw;
	  font-size: 4vw;
	}
	
	.empty-cart {
	  text-align: center;
	  padding: 10vw 0;
	  color: #999;
	}
	
	.cart-panel-footer {
	  padding: 4vw;
	  border-top: 1px solid #eee;
	  background: #f8f8f8;
	  position: sticky;
	  bottom: 0;
	}
	
	.cart-panel-footer p {
	  margin-bottom: 2vw;
	  font-size: 4vw;
	}
	
	.shipping-tip {
	  font-size: 3.5vw;
	  color: #ff5339;
	}
	
	.checkout-btn-panel {
	  width: 100%;
	  padding: 3vw;
	  background: #38CA73;
	  color: white;
	  border: none;
	  border-radius: 4px;
	  font-size: 4.5vw;
	  font-weight: bold;
	  cursor: pointer;
	  margin-top: 2vw;
	}
	
	.checkout-btn-panel:disabled {
	  background: #ccc;
	  cursor: not-allowed;
	}
	
	/* 购物车遮罩层 */
	.cart-panel-mask {
	  position: fixed;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  background: rgba(0, 0, 0, 0.5);
	  z-index: 1001;
	}
</style>